﻿using DatabaseCore;
using OGA.NPI.ICSH.ServiceBase.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using SystemCore.Helper;

namespace Export.SAP.Service
{
    public class ProductMovement
    {
        DatabaseCore.Dao.PlantDomExportDao plantDomExportProvider = new DatabaseCore.Dao.PlantDomExportDao();
        public DataSet getATP(string[] ProductionIDs)
        {
            var a = new OGA.NPI.CSH.SAPBLL.BLL.GTBLL("1", "");
            OGA.NPI.CSH.SAPBLL.Setting.WSSetting.SetWSGTProcess(Settings.Default.OGA_NPI_CSH_SAPBLL_WRSAPService_GIProcess);
            var reqgment = new OGA.NPI.ICSH.ServiceBase.Entities.RequestStockEntity();
            reqgment.RecHeader.RequestBy = "User1";

            foreach (var productionID in ProductionIDs)
            {
                var item = new OGA.NPI.ICSH.ServiceBase.Entities.RequestStockItemEntity();
                item.CheckRule = "";
                item.MaterialNo = productionID;
                //Todo need to loop all plant wating for tbl to get plant movement to export
                item.Plant = "8781";
                item.StockType = "A";
                item.StorageLocation = "0001";
                item.Unit = "PC";
                reqgment.RequestStockItem.Add(item);
            }

            var result = a.GetStockFromSAP(reqgment);
            var ds = new DataSet();
            if (result.Result)
            {
                
                var k = from tb in result.GetDataTable().AsEnumerable()
                        group tb by tb.Field<string>("Materialno") into g
                        select new 
                        {
                            TableName = g.Key,
                            Data = g
                        };

                foreach (var item in k)
                {
                    var dt = new DataTable(item.TableName);
                    foreach (var i in item.Data)
                    {
                        dt.Rows.Add(i);
                    }

                    ds.Tables.Add(dt);
                }
            }

            return ds;
        }

        public DataSet getATP(List<tbl_OrderDetail> Productions, bool IsAllPlant)
        {
            var a = new OGA.NPI.CSH.SAPBLL.BLL.GTBLL("1", "");
            var webService = WebConfigurationManager.AppSettings["OGA_NPI_CSH_SAPBLL_WRSAPService_IGIService"];
            OGA.NPI.CSH.SAPBLL.Setting.WSSetting.SetWSGTProcess(webService);
            var reqgment = new OGA.NPI.ICSH.ServiceBase.Entities.RequestStockEntity();
            reqgment.RecHeader.RequestBy = "User1";
            var plantProvider = new DatabaseCore.Dao.PlantDomExportDao();
            var plants = plantProvider.GetAllPlant();
            var plantsApply = plantProvider.GetAllPlantByCountryExport(Productions.FirstOrDefault().OrderNo);
            string[] dtColumns = { "Materialno", "Plant", "StorageLocation", "URQty", "QIQty", "BlackedQty", "ATPQty", "ItemId", "Unit" , "StockType" , "Location", "IsApply" };
            var ds = new DataSet();
            foreach (var production in Productions)
            {
                if (IsAllPlant)
                {
                    
                    foreach (var plant in plants)
                    {
                        var item = new OGA.NPI.ICSH.ServiceBase.Entities.RequestStockItemEntity();
                        item.CheckRule = "";
                        item.MaterialNo = production.MaterialNo;
                        //Todo need to loop all plant wating for tbl to get plant movement to export
                        item.Plant = plant.PlantDom;
                        item.StockType = "A";
                        item.StorageLocation = "0001";
                        item.Unit = "PC";
                        reqgment.RequestStockItem.Add(item);
                        //SystemCore.Helper.ExceptionHelper.LogAppError("request mat = " + item.MaterialNo + " plant = " + item.Plant);
                    }
                }
                else
                {
                    var item = new OGA.NPI.ICSH.ServiceBase.Entities.RequestStockItemEntity();
                    item.CheckRule = "";
                    item.MaterialNo = production.MaterialNo;
                    //Todo need to loop all plant wating for tbl to get plant movement to export
                    item.Plant = production.Plant;
                    item.StockType = "A";
                    item.StorageLocation = "0001";
                    item.Unit = "PC";
                    reqgment.RequestStockItem.Add(item);
                }
            }

            var result = a.GetStockFromSAP(reqgment);

            //SystemCore.Helper.ExceptionHelper.LogAppError(result.Result + " : " + result.MessageDescription + " : " + result.ResponseStockItem.Count());
            
            if (result.Result)
            {
                var k = from tb in result.GetDataTable().AsEnumerable()
                        group tb by tb.Field<string>("Materialno") into g
                        select new
                        {
                            TableName = g.Key,
                            Data = g
                        };

                foreach (var item in k)
                {
                    var dt1 = new DataTable(item.TableName);
                    foreach (var column in dtColumns)
                    {
                        dt1.Columns.Add(column);
                    }

                    foreach (var i in item.Data)
                    {
                        dt1.ImportRow(i);
                    }

                    for (int i = 0; i < dt1.Rows.Count  ; i++)
                    {
                        var plant = dt1.Rows[i]["Plant"].ToString();
                        var location = plants.FirstOrDefault(p => p.PlantDom == plant).Location;
                        dt1.Rows[i]["Location"] = location;
                        if (plantsApply.FirstOrDefault(p => p.PlantDom == plant) == null)
                        {
                            dt1.Rows[i]["IsApply"] = "false";
                        }
                        else{
                            dt1.Rows[i]["IsApply"] = "true";
                        }
                    }
                    
                    ds.Tables.Add(dt1);
                }
            }

            return ds;
        }

        public DataSet testGetATP(List<tbl_OrderDetail> Productions, bool IsAllPlant)
        {
            string[] dtColumns = { "Materialno", "Plant", "StorageLocation", "URQty", "UIQty", "BlackedQty", "ATPQty", "Location", "IsApply" };
            DataTable dt = new DataTable("productAtp");
            var plantProvider = new DatabaseCore.Dao.PlantDomExportDao();
            var plants = plantProvider.GetAllPlant();
            var plantsApply = plantProvider.GetAllPlantByCountryExport(Productions.FirstOrDefault().OrderNo);
            foreach (var column in dtColumns)
            {
                dt.Columns.Add(column);
            }

            foreach (var product in Productions)
            {
                var r1 = new Random();
                var r2 = new Random();
                var r3 = new Random();
                var r4 = new Random();

                
                if (IsAllPlant)
                {
                    foreach (var plant in plants)
                    {
                        r1 = new Random();
                        r2 = new Random();
                        r3 = new Random();
                        r4 = new Random();
                        dt.Rows.Add(new object[] { product.MaterialNo, plant.PlantDom, plant.Location, r1.Next(500), r2.Next(100), r3.Next(1000), r4.Next(10000) });
                    }
                }
                else
                {
                    dt.Rows.Add(new object[] { product.MaterialNo, product.Plant, "SB", r1.Next(500), r2.Next(100), r3.Next(1000), r4.Next(10000) });
                }
            }

            var ds = new DataSet();
            var k = from tb in dt.AsEnumerable()
                    group tb by tb.Field<string>("Materialno") into g
                    select new
                    {
                        TableName = g.Key,
                        Data = g
                    };

            foreach (var item in k)
            {
                var dt1 = new DataTable(item.TableName);
                foreach (var column in dtColumns)
                {
                    dt1.Columns.Add(column);
                }

                foreach (var i in item.Data)
                {
                    dt1.Rows.Add(i.ItemArray);
                }


                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    var plant = dt1.Rows[i]["Plant"].ToString();
                    //var location =
                    //dt1.Rows[i]["Location"] = location;
                    foreach (var plantApply in plantsApply)
                    {
                        if (plantApply.PlantDom == plant)
                        {
                            dt1.Rows[i]["IsApply"] = "true";
                            break;
                        }
                        else
                        {
                            dt1.Rows[i]["IsApply"] = "false";
                        }
                    }
                    
                }

                ds.Tables.Add(dt1);
            }

            return ds;
        }

        public ResponseGoodsMovementEntity productMove(List<tbl_Transaction> ProductsMapped)
        {
            var a = new OGA.NPI.CSH.SAPBLL.BLL.GTBLL("1", "");
            var con = WebConfigurationManager.AppSettings["ConnectionString"];
            var webService = WebConfigurationManager.AppSettings["OGA_NPI_CSH_SAPBLL_WRSAPService_IGIService"];
            OGA.NPI.CSH.SAPBLL.Setting.WSSetting.SetWSGTProcess(webService);
            OGA.NPI.ICSH.ServiceBase.Entities.RecordHeaderEntity processheader = null;
            try
            {
                processheader = a.GetProcessIDForGoodsTransferBetweenSite("1");
            }
            catch (Exception ex)
            {

                ExceptionHelper.LogAppError("error on get id " + ex.Message);
                return null;
            }
           

            var reqgment = new OGA.NPI.ICSH.ServiceBase.Entities.RequestGoodsMovementEntity();
            //SAPServiceTest.RequestGoodsMovementItemEntity reqgmentitem = new SAPServiceTest.RequestGoodsMovementItemEntity();

            foreach (var product in ProductsMapped)
            {
                if (product.Qty > 0)
                {
                    var reqgmentitem = new OGA.NPI.ICSH.ServiceBase.Entities.RequestGoodsMovementItemEntity();
                    reqgmentitem.MaterialNo = product.MaterialNo;
                    reqgmentitem.EntryQty = product.Qty;
                    reqgmentitem.EntryUOM = "PC";
                    reqgmentitem.Plant = product.Plant;
                    reqgmentitem.StorageLocation = "0001";
                    reqgmentitem.PlantDest = plantDomExportProvider.GetPlantExport(product.Plant).Trim();
                    reqgmentitem.StorageLocationDest = "0001";
                    ExceptionHelper.LogAppError("mat id " + reqgmentitem.MaterialNo + "qty " + reqgmentitem.EntryQty + " plant local = " + reqgmentitem.Plant + " Plant export = " + reqgmentitem.PlantDest);
                    reqgmentitem.GRShipTo = ""; // not sure do we need I47 
                    reqgment.RequestGoodsMovementItem.Add(reqgmentitem);
                }
            }

            reqgment.DocDate = DateTime.Today.ToString("yyyyMMdd");
            reqgment.PostingDate = DateTime.Today.ToString("yyyyMMdd");

            //processheader.ProcessID = processheader.ProcessID + 1000000;
            reqgment.RecHeader = processheader;
            ResponseGoodsMovementEntity result = null;
            try
            {
                if (reqgment.RequestGoodsMovementItem.Count == 0)
                {
                    return null;
                }
                result = a.GoodsTransferBetweenSite(reqgment);
            }
            catch (Exception ex)
            {
                ExceptionHelper.LogAppError("error on call service " + ex.Message);
                return null;
            }
            

            return result;
        }

        public ResponseGoodsMovementEntity productMove(List<tbl_Transaction> ProductsMapped, out int ProcessID)
        {
            var a = new OGA.NPI.CSH.SAPBLL.BLL.GTBLL("1", "");
            var con = WebConfigurationManager.AppSettings["ConnectionString"];
            var webService = WebConfigurationManager.AppSettings["OGA_NPI_CSH_SAPBLL_WRSAPService_IGIService"];
            OGA.NPI.CSH.SAPBLL.Setting.WSSetting.SetWSGTProcess(webService);
            OGA.NPI.ICSH.ServiceBase.Entities.RecordHeaderEntity processheader = null;
            try
            {
                processheader = a.GetProcessIDForGoodsTransferBetweenSite("1");
            }
            catch (Exception ex)
            {
                ProcessID = -1;
                ExceptionHelper.LogAppError("error on get id " + ex.Message);
                return null;
            }


            var reqgment = new OGA.NPI.ICSH.ServiceBase.Entities.RequestGoodsMovementEntity();
            //SAPServiceTest.RequestGoodsMovementItemEntity reqgmentitem = new SAPServiceTest.RequestGoodsMovementItemEntity();

            foreach (var product in ProductsMapped)
            {
                if (product.Qty > 0)
                {
                    var reqgmentitem = new OGA.NPI.ICSH.ServiceBase.Entities.RequestGoodsMovementItemEntity();
                    reqgmentitem.MaterialNo = product.MaterialNo;
                    reqgmentitem.EntryQty = product.Qty;
                    reqgmentitem.EntryUOM = "PC";
                    reqgmentitem.Plant = product.Plant;
                    reqgmentitem.StorageLocation = "0001";
                    reqgmentitem.PlantDest = plantDomExportProvider.GetPlantExport(product.Plant).Trim();
                    reqgmentitem.StorageLocationDest = "0001";
                    ExceptionHelper.LogAppError("mat id " + reqgmentitem.MaterialNo + "qty " + reqgmentitem.EntryQty + " plant local = " + reqgmentitem.Plant + " Plant export = " + reqgmentitem.PlantDest);
                    reqgmentitem.GRShipTo = ""; // not sure do we need I47 
                    reqgment.RequestGoodsMovementItem.Add(reqgmentitem);
                }
            }

            reqgment.DocDate = DateTime.Today.ToString("yyyyMMdd");
            reqgment.PostingDate = DateTime.Today.ToString("yyyyMMdd");

            //processheader.ProcessID = processheader.ProcessID + 1000000;
            reqgment.RecHeader = processheader;
            ResponseGoodsMovementEntity result = null;
            ProcessID = processheader.ProcessID;
            try
            {
                result = a.GoodsTransferBetweenSite(reqgment);
            }
            catch (Exception ex)
            {
                ExceptionHelper.LogAppError("error on call service " + ex.Message);
                return null;
            }
            return result;
        }
    }
}
